# -*- coding: utf-8 -*-
import scrapy
from scrapy import Spider, Request
from ..items import UserItem
import json


class ZhihuSpider(Spider):
    name = 'zhihu'
    allowed_domains = ['www.zhihu.com']
    start_urls = ['http://www.zhihu.com/']

    start_user = 'excited-vczh'

    user_url = 'https://www.zhihu.com/api/v4/members/{user}?include={include}'
    user_query = 'allow_message,is_followed,is_following,is_org,is_blocking,' \
                 'employments,answer_count,follower_count,articles_count,gender,badge[?(type=best_answerer)].topics'

    follows_url = 'https://www.zhihu.com/api/v4/members/excited-vczh/followees?' \
                  'include={include}&offset={offset}&limit={limit}'
    follows_query = 'data[*].answer_count,articles_count,gender,' \
                    'follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics'

    def start_requests(self):

        yield Request(self.user_url.format(user=self.start_user, include=self.user_query), callback=self.parse_user)
        yield Request(self.follows_url.format(user=self.start_user, include=self.follows_query, offset=0, limit=20),
                      callback=self.parse_follows)

    def parse_user(self, response):
        result = json.loads(response.text)
        item = UserItem()
        for field in item.fields:
            if field in result.keys():
                item[field] = result.get(field)
        yield item

        yield Request(
            self.user_url.format(user=result.get('url_token'), include=self.follows_query, offset=0, limit=20),
            callback=self.parse_user)

    def parse_follows(self, response):
        results = json.loads(response.text)
        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(self.user_url.format(user=result.get('url_token'), include=self.user_query),
                              callback=self.parse_user)

        if ('paging' in results.keys()) and ((results.get('paging').get('is_end')) == False):
            next_page = results.get('paging').get('next')

            str0 = "https://www.zhihu.com/api/v4/members/"
            pos1 = next_page.index("members")

            pos2 = next_page.index("include")

            str1 = next_page[pos1 + 8:pos2]

            include = 'include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower' \
                      'count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics'
            pos3 = next_page.index("&")
            str3 = next_page[pos3:]
            next_page0 = str0 + str1 + include + str3
            yield scrapy.http.Request(next_page0, callback=self.parse_follows)
